﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bing.Toolkit.Utility
{
    /// <summary>
    /// 获取中文汉字首字母
    /// </summary>
    public class FirstSpell
    {
        public static readonly Int32[] LIST_AREA = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };

        public static readonly String DEFAULT_STRING = "-1";

        public static String Convert(string val)
        {

            if (val.Trim().Length == 0) return DEFAULT_STRING;

            string result = DEFAULT_STRING;

            string str = val.Substring(0, 1);

            byte[] b = Encoding.Default.GetBytes(str);
            if (b.Length <= 1) return Encoding.Default.GetString(b);
            int currentArea = ((int)b[0] << 8) + (int)b[1];

            for (int i = 0, len = LIST_AREA.Length; i < len; i++)
            {
                if (LIST_AREA[i] <= currentArea && (i + 1) >= len ? true : LIST_AREA[i + 1] > currentArea)
                {
                    result = Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    break;
                }
            }

            return result;
        }
    }
}
